package com.amado.course50java8;

import java.util.Optional;
import java.util.function.Function;

import com.amado.course50java8.vo.Goods;
import com.amado.course50java8.vo.GoodsBrand;
import com.amado.course50java8.vo.GoodsCate;

public class Java806Optional2Map {

	public static void main(String[] args) {
		Goods goodsOne = new Goods(new GoodsCate(new GoodsBrand("adidas")));
		Goods goodsTwo = new Goods(new GoodsCate());
		System.out.println(getBrandName(goodsOne));
		System.out.println(getBrandNameByJava8(goodsOne));
		System.out.println(getBrandNameByJava8Equals(goodsOne));
		System.out.println(getBrandName(goodsTwo));
		System.out.println(getBrandNameByJava8(goodsTwo));
		System.out.println(getBrandNameByJava8Equals(goodsTwo));
	}

	public static String getBrandName(Goods goods) {
		if (goods != null) {
			GoodsCate goodsCate = goods.getGoodsCate();
			if (goodsCate != null) {
				GoodsBrand goodsBrand = goodsCate.getGoodsBrand();
				if (goodsBrand != null) {
					return goodsBrand.getBrandName();
				}
			}
		}
		return null;
	}

	// java optional 
	public static String getBrandNameByJava8(Goods goods) {
		return Optional.ofNullable(goods).map(t -> t.getGoodsCate()).map(t -> t.getGoodsBrand())
				.map(t -> t.getBrandName()).orElse(null);
	}
	// java optional
	public static String getBrandNameByJava8MethodRefernce(Goods goods) {
		return Optional.ofNullable(goods).map(Goods::getGoodsCate).map(GoodsCate::getGoodsBrand)
				.map(GoodsBrand::getBrandName).orElse(null);
	}

	// 等同于上面的函数
	public static String getBrandNameByJava8Equals(Goods goods) {
		return Optional.ofNullable(goods).map(new Function<Goods, GoodsCate>() {
			@Override
			public GoodsCate apply(Goods t) {
				return t.getGoodsCate();
			}
		}).map(new Function<GoodsCate, GoodsBrand>() {
			@Override
			public GoodsBrand apply(GoodsCate t) {
				return t.getGoodsBrand();
			}
		}).map(new Function<GoodsBrand, String>() {
			@Override
			public String apply(GoodsBrand t) {
				return t.getBrandName();
			}

		}).orElse(null);
	}
}
